package com.lscdu.gulimall.ruoyi_springboot.utis.config;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * @author 啊昌
 * @date 2024/9/8 21:25
 * MyBatisConfig
 */


@Configuration
@MapperScan("com.lscdu.gulimall.ruoyi_springboot.mapper")
public class MyBatisConfig {
	@Value("${mybatis.mapper-locations}")
	private String mapperLocations;

	@Value("${spring.datasource.url}")
	private String url;

	@Value("${spring.datasource.username}")
	private String username;

	@Value("${spring.datasource.password}")
	private String password;

	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;

	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setDriverClassName(driverClassName);
		return dataSource;
	}


	//配置FactoryBean
	@Bean(name = "sqlSessionFactoryBean")
	public SqlSessionFactoryBean sqlSessionFactoryBean() {
		SqlSessionFactoryBean sqlSessionFactoryBean = null;
		try {
			// 加载JNDI配置
			Context context = new InitialContext();
			// 实例SessionFactory
			sqlSessionFactoryBean = new SqlSessionFactoryBean();
			// 配置数据源
			sqlSessionFactoryBean.setDataSource(dataSource());
			// 加载MyBatis配置文件
			PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
			// 能加载多个，所以可以配置通配符(如：classpath*:mapper/**/*.xml)
			sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));
		} catch (Exception e) {
			System.out.println("创建SqlSession连接工厂错误：{}");
		}
		return sqlSessionFactoryBean;
	}

	@Bean
	public SqlSessionTemplate sqlSessionTemplate() throws Exception {
		SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactoryBean().getObject(), ExecutorType.BATCH);
		return sqlSessionTemplate;
	}
}
